// src/components/EChartsLineChart.tsx
import { LineChart } from 'echarts/charts';
import {
  GridComponent,
  LegendComponent,
  TitleComponent,
  TooltipComponent,
} from 'echarts/components';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import React, { useEffect, useRef } from 'react';

import { LineChartDataItem } from '@/types/know/know';

import type { EChartsOption, EChartsType, SeriesOption } from 'echarts';

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer,
]);

// 定义组件 Props 类型
interface EChartsLineChartProps {
  data: LineChartDataItem[];
  title?: string;
  color?: string;
  areaOpacity?: number;
  lineWidth?: number;
  gridOptions?: EChartsOption['grid'];
  className?: string;
  height?: number | string;
  text?: string;
}

const EChartsLineChart: React.FC<EChartsLineChartProps> = ({
  data,
  title = '',
  color,
  areaOpacity = 0.4,
  lineWidth = 1,
  gridOptions = {},
  className = '',
  height = '500px',
  text = '',
}) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<EChartsType | null>(null);

  useEffect(
    function setupChart() {
      if (!chartRef.current) return;
      chartInstance.current = echarts.init(chartRef.current) as unknown as EChartsType;

      // 获取最大值用于Y轴缩放
      const maxValue =
        Math.max(
          ...data.map((item) => {
            const value = text === '未知' ? item?.unknownCount : item?.feedbackCount;
            return value !== undefined ? value : 0;
          }),
        ) + 2 || 1;

      // 根据来源自动区分颜色（未显式传入 color 时）
      const lineColor = color || (text === '未知' ? '#1E6FFA' : '#07C375');
      const hexToRgb = (hex: string) => {
        const m = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        if (!m) return { r: 30, g: 111, b: 250 };
        return { r: parseInt(m[1], 16), g: parseInt(m[2], 16), b: parseInt(m[3], 16) };
      };
      const { r, g, b } = hexToRgb(lineColor);
      const areaTop = `rgba(${r}, ${g}, ${b}, 0.3)`;
      const areaBottom = `rgba(${r}, ${g}, ${b}, 0.05)`;
      const pointerColor = `rgba(${r}, ${g}, ${b}, 0.3)`;

      // 配置项
      const option: EChartsOption = {
        title: {
          text: title,
          left: 'center',
          textStyle: {
            color: '#333',
            fontSize: 18,
            fontWeight: 'bold',
          },
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: '#fff',
          borderColor: '#ddd',
          borderWidth: 1,
          textStyle: {
            color: '#1D2129',
            fontSize: 12,
          },
          axisPointer: {
            type: 'line',
            lineStyle: {
              color: pointerColor,
              width: 2,
            },
          },
          formatter: (params: any) => {
            const p = Array.isArray(params) ? params[0] : params;
            const date = p?.name ?? '';
            const value = p?.value ?? 0;
            const label = text === '未知' ? 'AI无法回答问题' : '用户反馈问题';
            return `
            <div style="padding:4px;width:160px;">
              <div style="color:'#87919D'; margin-bottom: 5px;border-bottom: 1px solid #f0f0f0; padding-bottom: 10px;">${date}</div>
              <div style="display:flex;align-items:center;justify-content:space-between;">
                <div style="display:flex;align-items:center;">
                  <div style="width:10px;height:10px;background:${lineColor};margin-right:8px;"></div>
                  <span style="color:#20242A;font-weight:bold;">${label}</span>
                </div>
                <b>${value}</b>
              </div>
            </div>
          `;
          },
          extraCssText:
            'box-shadow: 0 4px 12px rgba(0,0,0,0.1); border-radius: 8px; padding: 12px;',
        },
        grid: {
          left: '2%',
          right: '5%',
          bottom: '10%',
          top: '5%',
          containLabel: true,
          ...gridOptions,
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: data.map((item) => item._id),
          axisLine: {
            lineStyle: {
              color: '#e2e8f0',
            },
          },
          axisLabel: {
            color: '#87919D',
            formatter: (value: string) => {
              // 格式化日期显示为 MM-DD
              const date = new Date(value);
              return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date
                .getDate()
                .toString()
                .padStart(2, '0')}`;
            },
          },
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: maxValue * 1,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#e2e8f0',
            },
          },
          axisLine: {
            show: false,
          },
          axisLabel: {
            color: '#87919D',
            formatter: '{value}',
          },
        },
        series: [
          {
            name: '数据值',
            type: 'line',
            data:
              text === '未知'
                ? data.map((item) => item.unknownCount)
                : data.map((item) => item.feedbackCount),
            smooth: true,
            symbol: 'none',
            symbolSize: 8,
            itemStyle: {
              color: lineColor,
            },
            lineStyle: {
              width: 3,
              color: lineColor,
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: areaTop },
                { offset: 1, color: areaBottom },
              ]),
            },
            emphasis: {
              itemStyle: {
                color: '#fff',
                borderColor: lineColor,
                borderWidth: 2,
                shadowColor: lineColor,
                shadowBlur: 10,
              },
            },
          } as SeriesOption,
        ],
        animation: true,
        animationDuration: 1000,
        animationEasing: 'cubicOut',
      };

      chartInstance.current?.setOption(option);

      // 响应式调整
      const handleResize = () => chartInstance.current?.resize();
      window.addEventListener('resize', handleResize);

      return function cleanup() {
        window.removeEventListener('resize', handleResize);
        chartInstance.current?.dispose();
      };
    },
    [data, title, color, areaOpacity, lineWidth, gridOptions, text],
  );

  return <div ref={chartRef} className={`w-full rounded-xl ${className}`} style={{ height }} />;
};

export default EChartsLineChart;
